/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("yuanfa_pro_info",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.DomainModels;
using ATkg.BizAppProject.IServices;
using Microsoft.AspNetCore.Authorization;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.Extensions;
using Newtonsoft.Json.Linq;
using DocumentFormat.OpenXml.Bibliography;
using DGZImp.Core.DbSqlSugar;
using SqlSugar.Extensions;
using DocumentFormat.OpenXml.Drawing;
using DGZImp.Core.ManageUser;

namespace ATkg.BizAppProject.Controllers
{
    public partial class yuanfa_pro_infoController
    {
        private readonly Iyuanfa_pro_infoService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;

        [ActivatorUtilitiesConstructor]
        public yuanfa_pro_infoController(
            Iyuanfa_pro_infoService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }


        

        [HttpGet("get_yuanfa_product")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> get_yuanfa_product(string yuanfa)

        {
            Console.WriteLine(yuanfa);
            Console.WriteLine("get方法调用");
            var proname = yuanfa;

            var zaiku_all = 0;
            var zaixian_all = 0;
            var all_per_YF = new List<object>();

            var bj_info = await Service.get_yf_from_mes(proname);
            if(bj_info is int intValue && intValue == 0)
            {
                Console.WriteLine("返回值是 0");
            }
            else if (bj_info is List<object> dataList)
            {
                if(dataList.Any()){
                    var list_bj = JArray.FromObject(bj_info);
                    for (int i = 0; i < list_bj.Count; i++)
                    {
                        var per_ = JArray.FromObject(list_bj[i]);
                        for (int j = 0; j < per_.Count; j++)
                        {
                            var per_pro = per_[j];
                            zaiku_all += per_pro["在库数量"].Value<int>();
                            zaixian_all += per_pro["在线数量"].Value<int>();
                            per_pro["工厂"] = "北京工厂";
                            all_per_YF.Add(per_pro);
                        }
                    }
                }
                
            }

            var ak_info = await Service.get_yf_from_mes_ak(proname);
            Console.WriteLine("!!!!!!!!!!!");
            Console.WriteLine(ak_info);
            Console.WriteLine("````````````");

            if (ak_info is int intValueak && intValueak == 0)
            {
                Console.WriteLine("返回值是 0");
            }
            else if (ak_info is List<object> dataList)
            {
                if (dataList.Any())
                {
                    var list_ak = JArray.FromObject(ak_info);
                    for (int i = 0; i < list_ak.Count; i++)
                    {
                        var per_ = JArray.FromObject(list_ak[i]);
                        for (int j = 0; j < per_.Count; j++)
                        {
                            var per_pro = per_[j];
                            zaiku_all += per_pro["在库数量"].Value<int>();
                            zaixian_all += per_pro["在线数量"].Value<int>();
                            per_pro["工厂"] = "爱科工厂";
                            all_per_YF.Add(per_pro);
                        }
                    }
                }
                
            }

            


            var bf_info = await Service.get_yf_from_mes_bf(proname);

            if (bf_info is int intValuebf && intValuebf == 0)
            {
                Console.WriteLine("返回值是 0");
            }
            else if (bf_info is List<object> dataList)
            {
                if (dataList.Any())
                {
                    var list_bf = JArray.FromObject(bf_info);
                    for (int i = 0; i < list_bf.Count; i++)
                    {
                        var per_ = JArray.FromObject(list_bf[i]);
                        for (int j = 0; j < per_.Count; j++)
                        {
                            var per_pro = per_[j];
                            zaiku_all += per_pro["在库数量"].Value<int>();
                            zaixian_all += per_pro["在线数量"].Value<int>();
                            per_pro["工厂"] = "北方工厂";
                            all_per_YF.Add(per_pro);
                        }
                    }
                }
                
            }


            /////////////////////////////////////////////////////////
            ///       原发产品在线在库统计总和
            ///
            /////////////////////////////////////////////////////////
            // 转换为 JArray（方便遍历 JSON 对象）
            JArray jArray = JArray.FromObject(all_per_YF);
            var MPStore = 0;
            var MPOnline = 0;
            var HPStore = 0;
            var HPOnline = 0;
            var BPStore = 0;
            var BPOnline = 0;
            var CPStore = 0;
            var CPOnline = 0;
            foreach (JObject item in jArray)
            {
                // 提取字段（使用 JSON 中的键名，如 "名称"、"在库数量" 等）
                string 名称 = item["名称"]?.Value<string>(); // 安全获取字符串
                string 工厂 = item["工厂"]?.Value<string>();
                int 在库数量 = item["在库数量"]?.Value<int>() ?? 0; // 安全获取整数（默认值 0）
                int 在线数量 = item["在线数量"]?.Value<int>() ?? 0;
                string 客户图纸号 = item["客户图纸号"]?.Value<string>();
                string 产品代码 = item["产品代码"]?.Value<string>();


                if (名称.Contains("毛坯"))
                {
                    MPStore += item["在库数量"]?.Value<int>() ?? 0;
                    MPOnline += item["在线数量"]?.Value<int>() ?? 0;
                }
                else if (名称.Contains("黑片"))
                {
                    HPStore += item["在库数量"]?.Value<int>() ?? 0;
                    HPOnline += item["在线数量"]?.Value<int>() ?? 0;
                }
                else if (名称.Contains("白片"))
                {
                    BPStore += item["在库数量"]?.Value<int>() ?? 0;
                    BPOnline += item["在线数量"]?.Value<int>() ?? 0;
                }
                else if (!名称.Contains("/"))
                {
                    CPStore += item["在库数量"]?.Value<int>() ?? 0;
                    CPOnline += item["在线数量"]?.Value<int>() ?? 0;
                }
            }

            var final_data_info_total = new List<yuanfa_pro_info>();
            var result = Db.Queryable<yuanfa_pro_info>()  //  
                    .Where(m => m.YuanFaProName == proname)
                    .Select(m => new
                    {
                        m.YuanFaProName,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表

            if (result.Count > 0)
            {
                int rowsAffected = Db.Updateable<yuanfa_pro_info>()
                    .SetColumns(it => new yuanfa_pro_info
                    {
                        InStoreQty = zaiku_all.ToString(),
                        OnlineProQty = zaixian_all.ToString(),
                        MPStore = MPStore.ToString(),
                        MPOnline = MPOnline.ToString(),
                        HPStore = HPStore.ToString(),
                        HPOnline = HPOnline.ToString(),
                        BPStore = BPStore.ToString(),
                        BPOnline = BPOnline.ToString(),
                        CPStore = CPStore.ToString(),
                        CPOnline = CPOnline.ToString(),
                    })
                    .Where(it => it.YuanFaProName == proname) // 精确条件
                    .ExecuteCommand();
            }
            else
            {
                var data_3 = new yuanfa_pro_info
                {
                    YuanFaProName = proname,
                    InStoreQty = zaiku_all.ToString(),
                    OnlineProQty = zaixian_all.ToString(),
                    MPStore = MPStore.ToString(),
                    MPOnline = MPOnline.ToString(),
                    HPStore = HPStore.ToString(),
                    HPOnline = HPOnline.ToString(),
                    BPStore = BPStore.ToString(),
                    BPOnline = BPOnline.ToString(),
                    CPStore = CPStore.ToString(),
                    CPOnline = CPOnline.ToString(),
                };
                final_data_info_total.Add(data_3);

            }
            await Db.DoInsertAsync<yuanfa_pro_info>(final_data_info_total);

            /////////////////////////////////////////////////////////
            ///       各地原发产品代码分工序处理
            ///
            /////////////////////////////////////////////////////////

            
            // 遍历每个元素并提取数据
            
            var final_data_info_fen = new List<yuanfa_pro_info_fen>();
            foreach (JObject item in jArray)
            {
                // 提取字段（使用 JSON 中的键名，如 "名称"、"在库数量" 等）
                string 名称 = item["名称"]?.Value<string>(); // 安全获取字符串
                string 工厂 = item["工厂"]?.Value<string>();
                int 在库数量 = item["在库数量"]?.Value<int>() ?? 0; // 安全获取整数（默认值 0）
                int 在线数量 = item["在线数量"]?.Value<int>() ?? 0;
                string 客户图纸号 = item["客户图纸号"]?.Value<string>();
                string 产品代码 = item["产品代码"]?.Value<string>();


                
                var result_ = Db.Queryable<yuanfa_pro_info_fen>()  //  
                .Where(m => m.PerGX == 名称)
                .Select(m => new
                {
                    m.PerGX,
                })               // 选择 update_data 字段
                .ToList();                               // 执行查询并返回列表
                if (result_.Count > 0)
                {
                    int rowsAffected = Db.Updateable<yuanfa_pro_info_fen>()
                        .SetColumns(it => new yuanfa_pro_info_fen
                        {
                            InStoreQty = 在库数量.ToString(),
                            OnlineProQty = 在线数量.ToString()
                        })
                        .Where(it => it.PerGX == 名称) // 精确条件
                        .ExecuteCommand();
                }
                else
                {
                    var data_fen = new yuanfa_pro_info_fen
                    {
                        FactoryName = 工厂,
                        PerGX = 名称,
                        ProName = 产品代码,
                        PartnerBlueprintNo = 客户图纸号,
                        YuanFaProName = proname,
                        InStoreQty = 在库数量.ToString(),
                        OnlineProQty = 在线数量.ToString()
                    };
                    final_data_info_fen.Add(data_fen);
                }
            }
            await Db.DoInsertAsync<yuanfa_pro_info_fen>(final_data_info_fen);
            return all_per_YF;
            //return new List<object>
            //{
            //    1
            //};
        }

        [HttpGet("get_maopi_data")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> get_maopi_data()
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {

            Console.WriteLine("get方法调用");
            var result = await Service.get_maopi_data();
            var r = "1111";
            return result;
        }


        // 核心分类判断方法：根据名称确定分类
        private static string GetProductCategory(string productName)
        {
            if (string.IsNullOrEmpty(productName))
                return "成品"; // 异常名称默认归为成品（可按需调整）

            // 不含 "/" → 成品
            if (!productName.Contains("/"))
                return "成品";

            // 含 "/" → 取 "/" 后后缀判断
            string suffix = productName.Split('/')[1].Trim();
            return suffix switch
            {
                "毛坯" => "毛坯",
                "黑片" => "黑片",
                "白片" => "白片",
                _ => "成品" // 其他后缀（如无）默认归为成品
            };
        }

        [HttpGet("get_yuanfa_dingshi")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> get_yuanfa_dingshi()
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {

            Console.WriteLine("get方法调用testttttttttttttt");
            //var result = await Service.get_maopi_data();
            //var final_data_info_total = new List<yuanfa_pro_info>();
            var result_db = Db.Queryable<yuanfa_pro_info>()  //  
                    .Where(m => m.IsValid == 1)
                    .Select(m => new
                    {
                        m.YuanFaProName,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
            for(int x_ = 0; x_ < result_db.Count; x_++)
            {
                var per = result_db[x_];
                Console.WriteLine(per.YuanFaProName);
                Console.WriteLine("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww");
                string name_ = per.YuanFaProName;
                //var per_reuslt = get_yuanfa_product(name_);
                var proname = name_;

                var zaiku_all = 0;
                var zaixian_all = 0;
                var all_per_YF = new List<object>();
                

                var bj_info = await Service.get_yf_from_mes(proname);
                Console.WriteLine(proname);
                if (bj_info is int intValue && intValue == 0)
                {
                    Console.WriteLine("返回值是 0");
                }
                else if (bj_info is List<object> dataList)
                {
                    if (dataList.Any())
                    {
                        var list_bj = JArray.FromObject(bj_info);
                        for (int i = 0; i < list_bj.Count; i++)
                        {
                            var per_ = JArray.FromObject(list_bj[i]);
                            for (int j = 0; j < per_.Count; j++)
                            {
                                var per_pro = per_[j];
                                zaiku_all += per_pro["在库数量"].Value<int>();
                                zaixian_all += per_pro["在线数量"].Value<int>();
                                per_pro["工厂"] = "北京工厂";
                                all_per_YF.Add(per_pro);
                            }
                        }
                    }

                }

                var ak_info = await Service.get_yf_from_mes_ak(proname);
                Console.WriteLine(proname);
                Console.WriteLine("!!!!!!!!!!!");
                Console.WriteLine(ak_info);
                Console.WriteLine("````````````");

                if (ak_info is int intValueak && intValueak == 0)
                {
                    Console.WriteLine("返回值是 0");
                }
                else if (ak_info is List<object> dataList)
                {
                    if (dataList.Any())
                    {
                        var list_ak = JArray.FromObject(ak_info);
                        for (int i = 0; i < list_ak.Count; i++)
                        {
                            var per_ = JArray.FromObject(list_ak[i]);
                            for (int j = 0; j < per_.Count; j++)
                            {
                                var per_pro = per_[j];
                                zaiku_all += per_pro["在库数量"].Value<int>();
                                zaixian_all += per_pro["在线数量"].Value<int>();
                                per_pro["工厂"] = "爱科工厂";
                                all_per_YF.Add(per_pro);
                            }
                        }
                    }

                }




                var bf_info = await Service.get_yf_from_mes_bf(proname);
                Console.WriteLine(proname);

                if (bf_info is int intValuebf && intValuebf == 0)
                {
                    Console.WriteLine("返回值是 0");
                }
                else if (bf_info is List<object> dataList)
                {
                    if (dataList.Any())
                    {
                        var list_bf = JArray.FromObject(bf_info);
                        for (int i = 0; i < list_bf.Count; i++)
                        {
                            var per_ = JArray.FromObject(list_bf[i]);
                            for (int j = 0; j < per_.Count; j++)
                            {
                                var per_pro = per_[j];
                                zaiku_all += per_pro["在库数量"].Value<int>();
                                zaixian_all += per_pro["在线数量"].Value<int>();
                                per_pro["工厂"] = "北方工厂";
                                all_per_YF.Add(per_pro);
                            }
                        }
                    }

                }


                /////////////////////////////////////////////////////////
                ///       原发产品在线在库统计总和
                ///
                /////////////////////////////////////////////////////////
                // 转换为 JArray（方便遍历 JSON 对象）
                JArray jArray = JArray.FromObject(all_per_YF);
                var MPStore = 0;
                var MPOnline = 0;
                var HPStore = 0;
                var HPOnline = 0;
                var BPStore = 0;
                var BPOnline = 0;
                var CPStore = 0;
                var CPOnline = 0;
                foreach (JObject item in jArray)
                {
                    // 提取字段（使用 JSON 中的键名，如 "名称"、"在库数量" 等）
                    string 名称 = item["名称"]?.Value<string>(); // 安全获取字符串
                    string 工厂 = item["工厂"]?.Value<string>();
                    int 在库数量 = item["在库数量"]?.Value<int>() ?? 0; // 安全获取整数（默认值 0）
                    int 在线数量 = item["在线数量"]?.Value<int>() ?? 0;
                    string 客户图纸号 = item["客户图纸号"]?.Value<string>();
                    string 产品代码 = item["产品代码"]?.Value<string>();


                    if (名称.Contains("毛坯"))
                    {
                        MPStore += item["在库数量"]?.Value<int>() ?? 0;
                        MPOnline += item["在线数量"]?.Value<int>() ?? 0;
                    }
                    else if (名称.Contains("黑片"))
                    {
                        HPStore += item["在库数量"]?.Value<int>() ?? 0;
                        HPOnline += item["在线数量"]?.Value<int>() ?? 0;
                    }
                    else if (名称.Contains("白片"))
                    {
                        BPStore += item["在库数量"]?.Value<int>() ?? 0;
                        BPOnline += item["在线数量"]?.Value<int>() ?? 0;
                    }
                    else if (!名称.Contains("/"))
                    {
                        CPStore += item["在库数量"]?.Value<int>() ?? 0;
                        CPOnline += item["在线数量"]?.Value<int>() ?? 0;
                    }
                }

                var final_data_info_total = new List<yuanfa_pro_info>();
                var result = Db.Queryable<yuanfa_pro_info>()  //  
                        .Where(m => m.YuanFaProName == proname)
                        .Select(m => new
                        {
                            m.YuanFaProName,
                        })               // 选择 update_data 字段
                        .ToList();                               // 执行查询并返回列表

                if (result.Count > 0)
                {
                    int rowsAffected = Db.Updateable<yuanfa_pro_info>()
                        .SetColumns(it => new yuanfa_pro_info
                        {
                            InStoreQty = zaiku_all.ToString(),
                            OnlineProQty = zaixian_all.ToString(),
                            MPStore = MPStore.ToString(),
                            MPOnline = MPOnline.ToString(),
                            HPStore = HPStore.ToString(),
                            HPOnline = HPOnline.ToString(),
                            BPStore = BPStore.ToString(),
                            BPOnline = BPOnline.ToString(),
                            CPStore = CPStore.ToString(),
                            CPOnline = CPOnline.ToString(),
                        })
                        .Where(it => it.YuanFaProName == proname) // 精确条件
                        .ExecuteCommand();
                }
                else
                {
                    var data_3 = new yuanfa_pro_info
                    {
                        YuanFaProName = proname,
                        InStoreQty = zaiku_all.ToString(),
                        OnlineProQty = zaixian_all.ToString(),
                        MPStore = MPStore.ToString(),
                        MPOnline = MPOnline.ToString(),
                        HPStore = HPStore.ToString(),
                        HPOnline = HPOnline.ToString(),
                        BPStore = BPStore.ToString(),
                        BPOnline = BPOnline.ToString(),
                        CPStore = CPStore.ToString(),
                        CPOnline = CPOnline.ToString(),
                    };
                    final_data_info_total.Add(data_3);

                }
                await Db.DoInsertAsync<yuanfa_pro_info>(final_data_info_total);

                /////////////////////////////////////////////////////////
                ///       各地原发产品代码分工序处理
                ///
                /////////////////////////////////////////////////////////


                // 遍历每个元素并提取数据

                var final_data_info_fen = new List<yuanfa_pro_info_fen>();
                foreach (JObject item in jArray)
                {
                    // 提取字段（使用 JSON 中的键名，如 "名称"、"在库数量" 等）
                    string 名称 = item["名称"]?.Value<string>(); // 安全获取字符串
                    string 工厂 = item["工厂"]?.Value<string>();
                    int 在库数量 = item["在库数量"]?.Value<int>() ?? 0; // 安全获取整数（默认值 0）
                    int 在线数量 = item["在线数量"]?.Value<int>() ?? 0;
                    string 客户图纸号 = item["客户图纸号"]?.Value<string>();
                    string 产品代码 = item["产品代码"]?.Value<string>();



                    var result_ = Db.Queryable<yuanfa_pro_info_fen>()  //  
                    .Where(m => m.PerGX == 名称)
                    .Select(m => new
                    {
                        m.PerGX,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                    if (result_.Count > 0)
                    {
                        int rowsAffected = Db.Updateable<yuanfa_pro_info_fen>()
                            .SetColumns(it => new yuanfa_pro_info_fen
                            {
                                InStoreQty = 在库数量.ToString(),
                                OnlineProQty = 在线数量.ToString()
                            })
                            .Where(it => it.PerGX == 名称) // 精确条件
                            .ExecuteCommand();
                    }
                    else
                    {
                        var data_fen = new yuanfa_pro_info_fen
                        {
                            FactoryName = 工厂,
                            PerGX = 名称,
                            ProName = 产品代码,
                            PartnerBlueprintNo = 客户图纸号,
                            YuanFaProName = proname,
                            InStoreQty = 在库数量.ToString(),
                            OnlineProQty = 在线数量.ToString()
                        };
                        final_data_info_fen.Add(data_fen);
                    }
                }
                await Db.DoInsertAsync<yuanfa_pro_info_fen>(final_data_info_fen);

            }
            return result_db;
        }


    }

}
